(function() {
    // getting a reference to the main namespace if it exists - empty object otherwise
    var Prestatheme = window.Prestatheme = window.Prestatheme || {};
	
    Prestatheme.serialise = function() 
    {
		var item, stylesToString = '';
        try
        {
            Prestatheme.runDebug ("[COMMIT][serialise] Serialize style to be send through AJAX request");
			
			// Get styles settings
			if (Prestatheme.styles == undefined)
				Prestatheme.styles = new Array();
			
			for (var i=0; i<Prestatheme.styles.length; i++)
			{
				item = Prestatheme.styles[i];
				stylesToString += 'styles['+ item.selector +']['+ item.attribute +']='+ item.value +'&';
			}
			
			// Get design settings
			if (Prestatheme.designCfg == undefined)
				Prestatheme.designCfg = new Array();
			
			for (var i=0; i<Prestatheme.designCfg.length; i++)
			{
				item = Prestatheme.designCfg[i];
				stylesToString += 'design['+ item.elemName +']='+ item.classChoosen +'&';
			}
			
			// Removing the last '&'
			if (stylesToString != '')
				stylesToString = stylesToString.substring(0, stylesToString.length - 1);
			
			return stylesToString;
        }
        catch (e)
        {
            Prestatheme.manageError ('SER', e);
			return stylesToString;
        }
    };
	
	Prestatheme.commit = function ()
	{
        Prestatheme.runDebug ("[COMMIT][commit] Send updates to the server.");
        
        try
        {
			Prestatheme.sendAJAXRequest(Prestatheme.serialise());
		}
        catch (e)
        {
            Prestatheme.manageError ('COM', e);
        }
	};
	
    Prestatheme.deamon = function() 
    {
		var item, stylesToString = '';
        try
        {
            Prestatheme.runDebug ("[COMMIT][deamon] Run commit if there is some changes");
			
			Prestatheme.refresh();
			if (Prestatheme.updated)
			{
				Prestatheme.commit();
				Prestatheme.updated = false;
			}
        }
        catch (e)
        {
            Prestatheme.manageError ('RFS', e);
			return stylesToString;
        }
    };
    
    /* Send Ajax Request */
    Prestatheme.sendAJAXRequest = function(dataString, remotePage, asynchronous)
    {
        Prestatheme.runDebug ("[COMMIT][sendAJAXRequest] Runing an AJAX request.");
        
        try
        {
			// Before sending the request
			Prestatheme.beforeRunAJAX();
			
			// Defined params
			if (remotePage == null || remotePage == undefined || remotePage == NaN)
				remotePage = Prestatheme.baseurl;
			if (asynchronous == null || asynchronous == undefined || asynchronous == NaN)
				asynchronous = Prestatheme.ajaxAsyn;
			
            //send the request
            $.ajax({
            	type   : "POST",
            	url    : remotePage,
            	data   : dataString + "&ajax=1",
            	async  : asynchronous,
            	success: function(msg){
            		try {
						// After sending the request, in case of succes
                        Prestatheme.afterRunAJAX(msg, "OK");
                    } catch(error) {
						Prestatheme.updated = true;
                        Prestatheme.manageError ('UNK', error);
            		}
            	},
                error : function (request, settings) {
					// After sending request, in case of failed
					Prestatheme.updated = true;
                    Prestatheme.afterRunAJAX("KO");
                    Prestatheme.manageError ('ARF');
                }
            });
        }
        catch (e)
        {
			Prestatheme.updated = true;
            Prestatheme.manageError ('AJX', e);
        }
    };
    
    /* before sending */
    Prestatheme.beforeRunAJAX = function () 
    {
        Prestatheme.runDebug ("[COMMIT][beforeRunAJAX] Before running an AJAX request, we display a message (with a waiting picture) to show that.");
        
		Prestatheme.process++;
        //$('#notifications').html(Prestatheme.process);
		if (Prestatheme.process == 1)
        {
            $('#notifications').html("Please, wait while saving updates ...");
            $('#notifications').fadeOut();
        }
    };
    
    /* after sending */
    Prestatheme.afterRunAJAX = function (msg, msgCode) 
    {
        Prestatheme.runDebug ("[COMMIT][afterRunAJAX] After running the AJAX request, we remove information about the background running");
        
		Prestatheme.process--;
        // $('#requests_nb').html(Prestatheme.process);
        // $('#status_msg').append("|" + msgCode);
		if (Prestatheme.process == 0)
        {
			$('#notifications').fadeIn('slow', function () {$('#notifications').empty();});
        }
    };
})();